<template>
  <div class="px-[.75rem] py-0 h-[2rem] cursor-pointer box-border bg-[#FAF9F9] rounded-[1rem]" @click="goto">
    <div class="flex items-center h-full gap-2 text-[#1F2937]">
      <!-- {{ userSelect }} -->
      <div class="size-[1rem] rounded-full overflow-hidden">
        <img :src="$globalFn.imgPrefixUrl(userSelect.country_icon, 'national_flag')" alt="" class="size-full object-cover" />
      </div>
      <span class="font-medium text-[12px] uppercase">
        {{ userSelect.language_code }}
      </span>
      <span class="font-medium text-[12px] uppercase">/</span>
      <span class="font-medium text-[12px] uppercase">
        {{ userSelect.currency_code }}
      </span>
    </div>
  </div>
</template>
<script>
  import { debounce } from '@/static/js/common'
  export default {
    data() {
      return {
        // userSelect: {},
      }
    },
    created() {
      // 获取数据
      // this.getData();
    },
    computed: {
      // 使用计算属性替代 data，确保每次访问都获取最新的 cookie 值
      userSelect() {
        return (
          this.$cookies.get('userSelect') || {
            country_icon: '/flag/United%20States.png',
            country_code: 'US',
            currency_code: 'USD',
            language_code: this.$i18n.locale
          }
        )
      }
    },
    methods: {
      // 跳转
      goto: debounce(function () {
        // 当前页面路径 含有 language_currency 就 不跳转
        if (window.location.pathname.includes('language_currency')) return
        let currentUrl = window.location.pathname
        let search = window.location.search
        let locales = ['ar', 'de', 'es', 'fr', 'hi', 'id', 'it', 'ja', 'ko', 'ms', 'my', 'nl', 'pt', 'ro', 'ru', 'th', 'tl', 'vi', 'zh-tw', 'zh']
        // 修改正则表达式，确保只匹配开头的语言代码
        const regex = new RegExp(`^/(${locales.join('|')})(?=/|$)`, 'i')
        // 替换语言代码部分
        const result = currentUrl.replace(regex, '')
        let url = `${result}${search}`
        this.$router.push({
          path: this.localePath(`/language_currency?redirect=${encodeURIComponent(url)}`)
        })
      }, 200),
      getData() {
        this.userSelect = this.$cookies.get('userSelect') || {
          country_icon: '',
          country_code: '',
          currency_code: '',
          language_code: ''
        }
      }
    }
  }
</script>
<style lang="less" scoped></style>
